using Microsoft.AspNetCore.Http;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace CoreManager.Common
{
    /// <summary>
    /// IP地址获取工具类
    /// </summary>
    public static class IpHelper
    {
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        public static string GetClientIpAddress(this HttpContext context)
        {
            var ipAddress = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = context.Request.Headers["X-Real-IP"].FirstOrDefault();
            }
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = context.Connection.RemoteIpAddress?.ToString();
            }
            return ipAddress ?? "Unknown";
        }

        /// <summary>
        /// 检查IP地址是否为私有地址
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <returns>是否为私有地址</returns>
        public static bool IsPrivateIpAddress(this IPAddress ip)
        {
            var bytes = ip.GetAddressBytes();
            
            // 10.0.0.0/8
            if (bytes[0] == 10) return true;
            
            // 172.16.0.0/12
            if (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) return true;
            
            // 192.168.0.0/16
            if (bytes[0] == 192 && bytes[1] == 168) return true;
            
            return false;
        }

        /// <summary>
        /// 验证IP地址格式是否正确
        /// </summary>
        /// <param name="ip">IP地址字符串</param>
        /// <returns>是否为有效的IP地址</returns>
        public static bool IsValidIpAddress(this string ip)
        {
            return IPAddress.TryParse(ip, out var address) && 
                   address.AddressFamily == AddressFamily.InterNetwork;
        }

      
    }

}
